package com.tangruojie.service;

import com.tangruojie.properties.MyAppProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class InfoPrinter {

    /**
     * 为什么是全局可见？
     * 配置类是通过 @Component 注入 Spring 容器的，Spring 默认创建的 Bean 是 单例的（singleton），所以：
     * 所有注入的 MyAppProperties 都是同一个对象的引用
     * 改了 setName()，等于改了内存中这个对象的值
     * 其它类再访问这个对象的字段，看到的就是你刚刚改过的值
     * ------
     * 是否线程安全？
     * 如果你多个线程同时调用 setXxx() 和 getXxx()，就存在并发问题。
     * 解决方案：
     * 加上 volatile 或使用 AtomicXXX
     * 或者封装为不可变对象（immutable）再做切换
     * 或者使用配置中心（Nacos、Apollo）统一变更配置
     */

    private final MyAppProperties myAppProperties;

    public void print() {
        System.out.println(myAppProperties.getName());
        System.out.println(myAppProperties.getVersion());
        System.out.println(myAppProperties.getPort());
        System.out.println(myAppProperties.isEnableLogging());
        System.out.println(myAppProperties.getTime());
        System.out.println("==========================");
        System.out.println(myAppProperties.getAuthors());
        System.out.println("==========================");
        System.out.println(myAppProperties.getMetadata());
        System.out.println("==========================");
        System.out.println(myAppProperties.getDatasource());
        System.out.println(myAppProperties.getDatasource().getUrl());
        System.out.println(myAppProperties.getDatasource().getUsername());
        System.out.println(myAppProperties.getDatasource().getPassword());
        System.out.println("==========================");
        System.out.println(myAppProperties.getLimits());
        System.out.println(myAppProperties.getLimits().getMaxUsers());
        System.out.println(myAppProperties.getLimits().getTimeout());
        System.out.println(myAppProperties.getLimits().getTimeout().getConnect());
        System.out.println(myAppProperties.getLimits().getTimeout().getRead());
        System.out.println("==========================");
        System.out.println(myAppProperties.getUser());
        System.out.println(myAppProperties.getUser().getName());
        System.out.println(myAppProperties.getUser().getAge());
        System.out.println(myAppProperties.getUser().isMale());
        System.out.println("==========================");
        System.out.println(myAppProperties.getUserList());
    }

}
